package mod.service;

import cn.hutool.core.io.FileUtil;
import mod.pojo.DSTMod;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class DSTModService {

    Properties config;
    String dstPath;

    public DSTModService(String dstPath)
    {
        this.dstPath = dstPath;
    }

    // todo 读取文件配置项（待完成）

    /**
     * 读取文件配置项
     *
     * @param file 配置文件
     * @return 配置项类
     */
    public DSTMod readModInfo(File file) {
        return null;
    }


    /**
     * 读取指定目录下所有的mod
     *
     * @param modsPath 所有mod的目录
     * @return
     */
    public List<DSTMod> readAllModsInfo(Path modsPath) {
        // 先判断mods是不是目录
        boolean isDirectory = FileUtil.isDirectory(modsPath);
        if (!isDirectory) {
            return null;
        }
        List<DSTMod> dstModsList = new ArrayList<>();
        File directory = new File(modsPath.toString());
        File[] subDirectories = directory.listFiles(File::isDirectory);
        if (subDirectories != null) {
            for (File subDirectory : subDirectories) {
                String fileName = subDirectory.getName();
                if (fileName.startsWith("workshop-")) {
                    File file = new File(subDirectory.getAbsolutePath() + "/modinfo.lua");
                    DSTMod dstMod = readModInfo(file);
                    dstModsList.add(dstMod);
                }
            }
        }
        return dstModsList;
    }

    /**
     * 将用户配置的mod安装到游戏中
     * 先读取配置，在写入游戏安装目录的dedicated_server_mods_setup文件中
     */
    public int installModToServer(Path gameModPath) {
        System.out.println("安装mod到服务器.....");
        File file = new File(gameModPath.toString());
        if (!file.exists()) {
            System.err.println(gameModPath.toString() + "is not exist.");
            return -1;
        }
        List<String> modConfig = ModFileUtil.readModConfigFile(gameModPath);
        String serverPath = dstPath;
        if(serverPath == null)
        {
            System.err.println("dstPath config err.");
            return -1;
        } else {
            Path dstModPath = Paths.get(serverPath, "mods", "dedicated_server_mods_setup.lua");
            int flag = ModFileUtil.writeModConfigFile(modConfig, dstModPath);
            return flag;
        }
    }
}
